package com.soul.admin.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.soul.admin.exception.BusinessException;
import com.soul.admin.interceptor.AdminHolder;
import com.soul.admin.mapper.AdminMapper;
import com.soul.commons.constans.Constants;
import com.soul.commons.utils.JwtUtils;
import com.soul.model.db.Admin;
import com.soul.model.vo.AdminVo;
import org.apache.commons.codec.cli.Digest;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class AdminService extends ServiceImpl<AdminMapper, Admin> {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 保存生成的验证码
     *
     * @param uuid
     * @param code
     */
    public void saveCode(String uuid, String code) {
        String key = Constants.CAP_CODE + uuid;
        // 缓存验证码，10分钟后失效
        stringRedisTemplate.opsForValue().set(key, code, Duration.ofMinutes(10));
    }

    /**
     * 后台系统登录
     *
     * @return
     */
    public Map<String, String> login(String username, String password, String verificationCode, String uuid) {
        // 1. 用户名和密码较空
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) throw new BusinessException("用户名或面不能为空");
        // 2. 图片验证码较空
        if (StringUtils.isEmpty(verificationCode)) throw new BusinessException("输入的验证码不能为空");
        String key = Constants.CAP_CODE + uuid;
        // 3. 获取redis图片验证码
        String redisCode = stringRedisTemplate.opsForValue().get(key);
        // 4. 较空redis图片验证码
        if (StringUtils.isEmpty(redisCode)) throw new BusinessException("验证码失效，请重新获取验证码！");
        // 5. 比较用户和redis中验证码
        if (!redisCode.equals(verificationCode)) throw new BusinessException("输入的验证码不一致！");
        // 6. 删除redis中图片验证码(登录成功则删除图片验证码)
        stringRedisTemplate.delete(key);
        // 7. 查询用户名和密码
        Admin admin = this.query().eq("username", username).eq("password", DigestUtils.md5Hex(password)).one();
        // 用户不存在则抛出异常
        if (admin == null) throw new BusinessException("请正确输入用户名和密码");
        // 8. 调用Apache工具类生成token
        String token = JwtUtils.createToken(admin.getId(), admin.getUsername());
        // 9. 用户信息保存redis并设置有效期时间
        String tokenKey = "TOKEN_" + token;
        String redisAdmin = JSON.toJSONString(admin);
        stringRedisTemplate.opsForValue().set(tokenKey,redisAdmin,30, TimeUnit.MINUTES);
        // 10. 返回token给前端浏览器存储
        Map<String, String> map = new HashMap<>();
        map.put("token", token);
        return map;
    }

    /**
     *  后台系统退出
     * @return
     */
    public void logout(String authorization) {
        String token = authorization.replace("Bearer ", authorization);
        String tokenKey = "TOKEN_" + token;
        stringRedisTemplate.delete(tokenKey);
    }

    /**
     *  用户基本信息
     * @return
     */
    public AdminVo profile() {
        return AdminVo.init(AdminHolder.getAdmin());
    }
}